﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class UserManagement : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {


        if (!HttpContext.Current.Request.IsAuthenticated)
        {
            Response.Redirect("~/login.aspx");
        }
        else
        {
             if (!Page.IsPostBack)
            {
           


               
                //Create Connection String And SQL Statement
                string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;

                SqlConnection sqlConnection = new SqlConnection(strConnection);

                string findUserProfile = "SELECT UserName, FirstName, LastName, Contact,LastLoginDate, EmailAddress, Nationality, Occupation, Company, AccountAmount, ReferalCode FROM [User] where UserName ='" + User.Identity.Name + "'";

                SqlCommand command1 = new SqlCommand(findUserProfile, sqlConnection);

                sqlConnection.Open();

                command1.ExecuteNonQuery();
                DataSet dsPwd = new DataSet();
                SqlDataAdapter dAdapter = new SqlDataAdapter(command1);

                dAdapter.Fill(dsPwd);

                
                LabelUserName.Text = User.Identity.Name.ToString();
                TextBoxFirstName.Text = dsPwd.Tables[0].Rows[0]["FirstName"].ToString();
                TextBoxLastName.Text = dsPwd.Tables[0].Rows[0]["LastName"].ToString();
                Country.SelectedValue = dsPwd.Tables[0].Rows[0]["Nationality"].ToString();
                TextBoxEmail.Text = dsPwd.Tables[0].Rows[0]["EmailAddress"].ToString();
                TextBoxContact.Text = dsPwd.Tables[0].Rows[0]["Contact"].ToString();
                TextBoxOccupation.Text = dsPwd.Tables[0].Rows[0]["Occupation"].ToString();
                TextBoxCompany.Text = dsPwd.Tables[0].Rows[0]["Company"].ToString();
                LabelAccountAmount.Text = dsPwd.Tables[0].Rows[0]["AccountAmount"].ToString();
                RefererID.Text = dsPwd.Tables[0].Rows[0]["ReferalCode"].ToString();
            

                sqlConnection.Close();

                string user = (string)(Session["Userfield"]);

                if (user == "admin")
                {
                    AdminHyperLink1.Visible = true;

                }
                else
                {
                    AdminHyperLink1.Visible = false;

                }


          
            }
     
     }
    
  }






      protected void Button1_Click(object sender, EventArgs e)
    {
          
        string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;

        SqlConnection sqlConnection = new SqlConnection(strConnection);

        try
        {

           
                lbl_msg2.Visible = false;
                sqlConnection.Open();

                SqlCommand cmd2 = new SqlCommand("select EmailAddress from [User] where EmailAddress='" + TextBoxEmail.Text.Trim() + "' and UserName='" + User.Identity.Name.Trim() + "'", sqlConnection);


                SqlDataReader dr = cmd2.ExecuteReader();




                //Check if email address of user is same as database before updating other fields.     


                if (dr.HasRows)
                {
                    

                        //Update user data

                        dr.Close();
                       
                        String updateSQL = "Update [User] set FirstName='" + TextBoxFirstName.Text.Trim() + "',LastName='" + TextBoxLastName.Text.Trim() + "',EmailAddress='" + TextBoxEmail.Text.Trim() + "',Nationality='" + Country.SelectedValue.ToString() + "',Contact='" + TextBoxContact.Text.Trim() + "',Occupation='" + TextBoxOccupation.Text.Trim() + "',Company='" + TextBoxCompany.Text.Trim() + "' where UserName ='" + User.Identity.Name.Trim() + "'";

                        //Create SQL Command And Sql Parameters

                        SqlCommand cmd3 = new SqlCommand(updateSQL, sqlConnection);

                      
                        cmd3.ExecuteNonQuery();
                        
                        lbl_msg2.Visible = false;
                       
                        Response.Write("<script language='javascript'>alert('Updated Profile Record Successful.');window.location.href='UserProfile.aspx'</script>");                

                   

                  
                }



                else
                {
                    //Check if email address given is used already.

                    SqlCommand cmd = new SqlCommand("select EmailAddress from [User] where EmailAddress='" + TextBoxEmail.Text.Trim() + "'", sqlConnection);
                    dr.Close();
                    dr = cmd.ExecuteReader();


                    if (dr.HasRows)
                    {

                        lbl_msg2.Visible = true;
                        lbl_msg2.Text = "Email already used";

                    }

                    else
                    {
                        //Update new email address with rest of records fields

                        dr.Close();
                        
                        String updateSQL = "Update [User] set FirstName='" + TextBoxFirstName.Text.Trim() + "', LastName='" + this.TextBoxLastName.Text.Trim() + "',EmailAddress='" + TextBoxEmail.Text.Trim() + "', Nationality='" + Country.SelectedValue.ToString() + "',Contact='" + TextBoxContact.Text + "',Occupation='" + TextBoxOccupation.Text.Trim() + "',Company='" + TextBoxCompany.Text.Trim() + "' where UserName ='" + User.Identity.Name.Trim() + "'";

                        //Create SQL Command And Sql Parameters

                        SqlCommand cmd3 = new SqlCommand(updateSQL, sqlConnection);
       
                        cmd3.ExecuteNonQuery();
                        
                        lbl_msg2.Visible = false;
                        

                        Response.Write("<script language='javascript'>alert('Updated Profile Record Successful.');window.location.href='UserProfile.aspx'</script>");             


                    }



                }


            }

      

        catch (SqlException ex)
        {
            string errorMessage = "Error in Updating user";
            errorMessage += ex.Message;
            throw new Exception(errorMessage);

        }

        finally
        {
            sqlConnection.Close();

        }



    }




    
}